package com.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;


import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DaoSupport;
import org.springframework.objenesis.strategy.StdInstantiatorStrategy;

import com.spring.model.Student;
import com.spring.model.User;

public class StudentDaoImpl implements StudentDao {
	
	private SessionFactory sessionFactory;
	


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}



	@Override
	public void addStudent(Student student) {
		// TODO Auto-generated method stub
          sessionFactory.getCurrentSession().save(student);
	}



	@Override
	public List<Student> getAllStudent() {
		// TODO Auto-generated method stub
		
		String hql="from Student";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}



	@Override
	public void delStudent(String id) {
		// TODO Auto-generated method stub
		String hql="delete Student student where student.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);
		 query.executeUpdate();
	}



	@Override
	public void updateStudent(Student student) {
		// TODO Auto-generated method stub
		String hql="update Student student set student.name=?,student.age=? where student.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0,student.getName());
		query.setString(1,student.getAge());
		query.setString(2,student.getId());
		query.executeUpdate();
		
	}



	@Override
	public Student getStudent(String id) {
		// TODO Auto-generated method stub
		String hql="from Student student where student.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);
		return (Student) query.uniqueResult();
		
	}



	@Override
	public boolean login(String user, String password) {
		// TODO Auto-generated method stub
		  if(user==null){
	            user="";
	        }
	        if(password==null){
	            password="";
	        }
	        List<User> list = null;
		String hql="select user.user ,user.password from User as user where user.user='"+user+"' and user.password = '"+password+"'";
		  try {
	           
	            Query query =sessionFactory.getCurrentSession().createQuery(hql);
	            System.out.println("@@@@@@@@@");
	            list = query.list();
	            
	        } catch (DataAccessException e) {
	            // TODO: handle exception
	            return false;
	        }
	        
	        if(list.isEmpty()){
	            return false;
	        }
	            return true;
	   


	}

}
